const express=require('express');
const cookieParser=require('cookie-parser');
const cookieSession=require('cookie-session');
const useServer=require('../service/userService');

var router=express.Router();

router.use('/loginPage.html',async function (req,res,next) {
    var user=req.cookies.user;
    //console.log('view router:'+user.role);
    if(user=={}||user==undefined){
        //1.loginPage.html
        console.log('cookie is null');
        next();
    }else if(user.role=='admin'){
        console.log('role admin isn\' auto login');
        next();
    } else{
        //自动登录
        //res.redirect()
        //console.log(2222222222);
        var data=await useServer.logincookie(user);

        //console.log("data:"+data);
        console.log('5555555555555555555'+data.user);
        if(data.success){
            req.session.user=data.user;
            //客户端发出的信息
            res.redirect('/views/pages/user1.html');
            //2.user1.html
        }else{
            //3.loginPage.html
            next();
        }
    }
});

//进行pages页面，必须是已登录状态，否则全部进入/views/loginPage.html
router.use('/pages',function (req,res,next){
    console.log('pages');
    var user=req.session.user;
    if(user==[]||user=={}||user==undefined||user==''){
        res.redirect('/views/loginPage.html');
    }else{
        next();
        //console.log(res);
    }
});

router.use('/admin',function(req,res,next){
    //console.log('/admin');
    var user=req.session.user;
    if(user==[]||user=={}||user==undefined||user==''){
        res.redirect('/views/loginPage.html');
    }else if(user.role=="user"){
        res.redirect('/views/loginPage.html');
    }else{
        next();
        //console.log(res);
    }
});
exports.router=router;